﻿using System.Reflection;

namespace ExcelUnity.Core;

public class ColumnProperty
{
    public ColumnProperty(PropertyInfo property)
    {
        Name = property.GetCustomAttribute(typeof(ColumnNameAttribute)) is ColumnNameAttribute nameAttr ? nameAttr.Name : property.Name;
        
        PropertyInfo = property;
    }

    /// <summary>
    /// 列名
    /// </summary>
    public string Name { get; set; }
    
    /// <summary>
    /// 属性所在的列索引
    /// </summary>
    public int ColumnIndex { get; set; }
    
    /// <summary>
    /// 列对应的对象属性
    /// </summary>
    public PropertyInfo PropertyInfo { get; set; }
    
    /// <summary>
    /// 获取该属性在cell中展示的文本
    /// </summary>
    /// <param name="target"></param>
    /// <returns></returns>
    public string GetCellValue(object target)
    {
        var objectValue = PropertyInfo.GetValue(target);

        string cellValue = string.Empty;
        if (objectValue != null)
        {
            if (PropertyInfo.PropertyType == typeof(DateTime) || PropertyInfo.PropertyType == typeof(DateTime?))
            {
                cellValue = ((DateTime)objectValue).ToString("yyyy-MM-dd HH:mm:ss");
            }
            else
            {
                cellValue = objectValue.ToString();
            }
        }
        return cellValue;
    }
}